import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from 'views/Home'
import { isLogin } from 'utils'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: '首页',
    meta: {
      needLogin: false,
      keepAlive: true
    },
    component: Home
  },
  {
    path: '/cate',
    name: '分类',
    meta: {
      needLogin: false
    },
    component: () => import('views/Cate')
  },
  {
    path: '/cart',
    name: '购物车',
    meta: {
      needLogin: true
    },
    component: () => import('views/Cart')
  },
  {
    path: '/user',
    name: '我的',
    meta: {
      needLogin: true
    },
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ 'views/User')
  },
  {
    path: '/detail',
    name: '详情页',
    meta: {
      needLogin: false
    },
    component: () => import('views/Detail')
  },
  {
    path: '/login',
    name: '登录页',
    meta: {
      needLogin: false
    },
    component: () => import('views/Login')
  },
  {
    path: '/register',
    name: '注册页',
    meta: {
      needLogin: false
    },
    component: () => import('views/Register')
  },
  {
    path: '/itemlist/:listId/:listName',
    name: '列表页',
    meta: {
      needLogin: false
    },
    component: () => import('views/ItemList')
  },
  {
    path: '/contadd',
    name: 'contadd',
    meta: {
      needLogin: true
    },
    component: () => import('views/ContentAdd')
  },
  {
    path: '/contlists',
    name: 'contlists',
    meta: {
      needLogin: true
    },
    component: () => import('views/ContentLists')
  },
  {
    path: '/updatecont',
    name: 'updatecont',
    meta: {
      needLogin: true
    },
    component: () => import('views/UpdateCon')
  },
  {
    path: '/confirmorder',
    name: 'confirmorder',
    meta: {
      needLogin: true
    },
    component: () => import('views/ConfirmOrder')
  },
  {
    path: '/search',
    name: 'search',
    meta: {
      needLogin: false
    },
    component: () => import('views/Search')
  },
  {
    path: '/searchitems',
    name: 'searchitems',
    meta: {
      needLogin: false
    },
    component: () => import('views/SearchItems')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 登录鉴权
router.beforeEach((to, from, next) => {
  localStorage.setItem('boforeFrom', from.path)
  if (!to.meta.needLogin) {
    next()
  } else {
    if (isLogin()) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  }
})

export default router
